<?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Account;


class Authenticate extends Middleware
{
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('Authorization');
 
        if (!$token) {
            return response()->json(['error' => '未提供认证信息','error_code'=>'401'], 401);
        }
 
        $account = Account::where('token', $token)->first();
 
        if (!$account) {
            return response()->json(['error' => '无效的认证信息','error_code'=>'401'], 401);
        }
 
        $request->account = $account;
 
        return $next($request);
    }

    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}
